<template>
  <div id="wrapper">
    <el-card class="box-card">
      <el-row>
        <el-col :xs="24" :sm="24" :lg="24" class="border"></el-col>
        <el-col :xs="4" :sm="4" :lg="4" style="float:right;margin-top: -30px;">
          <el-tooltip placement="top">
            <div slot="content">
              操作指南
            </div>
            <div class="icon-item">
              <a href="https://thundersoft.feishu.cn/docs/doccn2rVJ58GA0OX4CCy9gqIp4B#" target="_blank">
                <img :src="logo">
              </a>
            </div>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :md="10" :lg="8" class="col-box">
          <span class="col-span">立项状态：</span>
          <el-select v-model="params['status']" style="width:70%" placeholder="请选择" @change="changeFilter" clearable>
            <el-option v-for="(v,i) in statusList" :key="i" :label="v.text" :value="v.value"> </el-option>
          </el-select>
        </el-col>
        <el-col :xs="24" :md="10" :lg="8" class="col-box">
          <span class="col-span">关键字：</span>
          <el-input v-model="params['keywords']" placeholder="查询关键字,项目名称/事业群/客户名称/项目经理" style="width:70%" @change="changeFilter"></el-input>
        </el-col>

        <el-col :xs="24" :md="10" :lg="8" class="col-box">
          <label for="cascader">选择项目:</label>
            <el-cascader
              :key="isRescourceShow"
              placeholder="请选择项目"
              :props="props"
              :options="projectListOptions"
              filterable
              clearable
              collapse-tags
              :show-all-levels="false"
              @change="searchPro"
              style="margin-left: 10px"
            >
            </el-cascader>
        </el-col>

        <!-- <el-col :xs="24" :md="4" :lg="8" style="text-align: right;float:right;margin-top:10px"> -->
          <!-- <el-button type="primary" @click="createProject()" style="float:right;margin:0 10px 10px 0">新增</el-button> -->
          <!-- <el-button type="warning" @click="showManPower()" style="margin-right: 20px;">正式工时预览</el-button> -->
          <!-- style="float:right;margin:0 10px 10px 0" @click="showDetile()" v-show="showCheck" -->
        <!-- </el-col> -->
      </el-row>
      <el-table class="marT" :data="tableData" row-key="id" :header-cell-style="{background:'#eef1f6'}" style="width:100%;"  v-loading="loading">
        <!-- @expand-change="getChildList" -->
        <!-- <el-table-column type="expand">
          <template slot-scope="expands">
            <el-table
             :id="'innerTable'+expands.row.id"
              :data="expands.row.childData"
              border
              style="width: 90%">
              <el-table-column property="site_power.technical_field.name" label="技术领域" align="center" fixed="left" width="250">
                <template slot-scope="scope">
                  <el-tooltip placement="top" effect="light">
                    <div slot="content">
                      <span v-if="scope.row.site_power.technical_field">
                        {{ scope.row.site_power.technical_field.parent_display }}
                      </span>
                      <span v-if="scope.row.site_power.technical_field">
                        {{ scope.row.site_power.technical_field.name }}
                      </span>
                    </div>
                    <el-tag type="primary" v-if="scope.row.site_power.technical_field">
                      {{scope.row.site_power.technical_field.name.length > 20 ? scope.row.site_power.technical_field.name.substring(0,19)+'...':scope.row.site_power.technical_field.name}}
                    </el-tag>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column align="center" v-for="(v,i) in expands.row.week_col" :key="i" :property="v" :label="week2date(v)" width="120">
                <template slot-scope="scope">
                  
                  <div class="borders">需求：{{ scope.row.result.need[v].number.toFixed(1) }}</div>
                  <div class="hover-div">
                    <el-tooltip placement="right" v-if="scope.row.result.total[v].children && scope.row.result.total[v].children.length" effect="light">
                      <div slot="content">
                        <span v-for="(val,ind) in scope.row.result.total[v].children" :key="ind">{{ val.employee.dept }} - {{ val.employee.name }}（{{val.spend}}）<br/></span></div>
                        <span>已分配：{{ scope.row.result.total[v].number.toFixed(1) }}</span>
                    </el-tooltip>
                    <span v-else>已分配：{{ scope.row.result.total[v].number.toFixed(1) }}</span>
                  </div>
                </template>
            </el-table-column>
            </el-table>
          </template>
        </el-table-column> -->
        <el-table-column align="center" property="project_name" label="项目名称"></el-table-column>
        <el-table-column align="center" property="dept" label="立项事业部"></el-table-column>
        <el-table-column align="center" property="customer" label="客户"></el-table-column>
        <el-table-column align="center" property="project_manager" label="项目经理"></el-table-column>
        <!-- <el-table-column align="center" property="project_type" label="项目类型"></el-table-column> -->
        <el-table-column align="center" property="status" label="立项状态">
            <template slot-scope="scope">
                <el-tag v-if="scope.row.status == 0" type="success" effect="plain">变更</el-tag>
                <el-tag v-if="scope.row.status == 1" type="primary" effect="plain">封存</el-tag>
                <el-tag v-if="scope.row.status == 2" type="success" effect="plain">结项</el-tag>
                <el-tag v-if="scope.row.status == 3" type="primary" effect="plain">立项</el-tag>
                <el-tag v-if="scope.row.status == 4" type="success" effect="plain">终止</el-tag>
                <el-tag v-if="scope.row.status == 5" type="primary" effect="plain">研发结项</el-tag>
                <el-tag v-if="scope.row.status == 6" type="primary" effect="plain">预立项</el-tag>
            </template>
        </el-table-column>
        <el-table-column align="center" label="需求总人周">
          <template slot-scope="scope">{{scope.row.need_total_person_weeks.toFixed(1)}}</template>
        </el-table-column>
        <el-table-column align="center" label="需求总人月">
          <template slot-scope="scope">{{scope.row.need_total_person_months.toFixed(1)}}</template>
        </el-table-column>
        <el-table-column align="center" label="匹配总人周">
          <template slot-scope="scope">{{scope.row.get_total_person_weeks.toFixed(1)}}</template>
        </el-table-column>
        <el-table-column align="center" label="需求状态">
            <template slot-scope="scope">
                <el-tag v-if="scope.row.rate == 100" type="success">已确定</el-tag>
                <el-tag v-else type="warning">未确定</el-tag>
            </template>
        </el-table-column>
        <el-table-column align="center" property="rate" label="需求满足占比">
            <template slot-scope="scope">
                <span>{{scope.row.rate}}%</span>
            </template>
        </el-table-column>
        <el-table-column align="center" property="update_name" label="更新人员">
          <template slot-scope="scope">
            <span>{{scope.row.update_name ? scope.row.update_name : scope.row.create_name}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" property="update_time" label="更新时间" width='100'>
            <template slot-scope="scope">
                <span>{{scope.row.update_time_show}}</span>
            </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" width="150">
          <template slot-scope="scope">
            <!-- <div>
              <el-button type="text" size="mini" @click="viewProject(scope.row.id)">
                查看项目信息
              </el-button>
            </div> -->
            <div>
              <el-button type="text" size="mini" @click="editProject(scope.row)" :disabled="scope.row.status != 0 && scope.row.status != 3 && scope.row.status != 6">
                修改工数预测
              </el-button>
              <!-- <el-button type="text" size="mini" @click="checkProject(scope.row)">
                查看工时详情
              </el-button> -->
            </div>
            <div>
              <el-popconfirm v-if="scope.row.can_edit && scope.row.type == 'resource' && scope.row.rate == 0" title="确定删除吗？" @onConfirm="delProject(scope.row.id)">
                <el-button slot="reference" type="text" size="mini" style="color: red;margin-right: 10px">
                  删除
                </el-button>
              </el-popconfirm>
              <el-button v-if="scope.row.can_edit" type="text" size="mini" @click="shareProject(scope.row.id)">
                协同维护
              </el-button>
            </div>
            
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-show="tableTotal > 10" background layout="prev, pager, next" :page-size="params.pageSize" @size-change="tableSizeChange" @current-change="tableCurrentChange" :current-page="params.pageNo" style="text-align: center" :total="tableTotal">
      </el-pagination>
    </el-card>
    <el-dialog title="项目查看" :visible.sync="dialogVisible" width="90%" :destroy-on-close="true">
      <projectform v-if="dialogVisible" :formData="itemFormData" :calculated="calculated" ref="dialogform" ></projectform>
      <span slot="footer" class="dialog-footer">
      </span>
    </el-dialog>
    <el-dialog title="项目编辑" :visible.sync="dialogEditVisible" width="90%" @close='editProjectOver' :destroy-on-close="true">
      <projectform v-if="dialogEditVisible" :formData="itemFormData" :calculated="calculated" canEdit="true"></projectform>
      <span slot="footer" class="dialog-footer">
      </span>
    </el-dialog>
    <el-dialog title="协同维护" :visible.sync="shareVisible" width="60%" :destroy-on-close="true">
      <ShareDialog v-if="shareVisible" :shareId="shareId"></ShareDialog>
    </el-dialog>
    <el-dialog title="正式工时预览" :visible.sync="checkManPowerVisible" width="90%" :destroy-on-close="true">
      <CheckManPowerDialog v-if="checkManPowerVisible" ></CheckManPowerDialog>
    </el-dialog>

    <el-dialog title="工时详情" :visible.sync="showHours" width="90%">
      <el-table
        id="innerTable"
        :data="gridData"
        :cell-class-name="addClass"
        border
        v-loading="isshowHours">
        <el-table-column label="技术领域" align="center" fixed="left" width="200">
          <template slot-scope="scope">
            <el-tooltip placement="top" effect="light">
              <div slot="content">
                <span v-if="scope.row.site_power.technical_field">
                  {{ scope.row.site_power.technical_field.parent_display }}
                </span>
                <span v-if="scope.row.site_power.technical_field">
                  {{ scope.row.site_power.technical_field.name }}
                </span>
              </div>
              <el-tag type="primary" v-if="scope.row.site_power.technical_field">
                {{scope.row.site_power.technical_field.name.length > 20 ? scope.row.site_power.technical_field.name.substring(0,19)+'...':scope.row.site_power.technical_field.name}}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" label="汇总" width="120" fixed="left">
          <template slot-scope="scope">
            <div class="borders">需求：{{ scope.row.result.sum_need.toFixed(1) }}</div>
            <div>已分配:{{scope.row.result.sum_get.toFixed(1)}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" v-for="(v,i) in weekCol" :key="i" :label="week2date(v)" :property="v" width="120" type="cell">
          <template slot-scope="scope">
            <div class="borders">需求：{{ scope.row.result.need[v].number.toFixed(1) }}</div>
            <div class="hover-div">
              <el-tooltip placement="right" v-if="scope.row.result.total[v].children && scope.row.result.total[v].children.length" effect="light">
                <div slot="content">
                  <span v-for="(val,ind) in scope.row.result.total[v].children" :key="ind">{{ val.employee.dept }} - {{ val.employee.name }}（{{val.spend}}）<br/></span></div>
                  <span>已分配：{{ scope.row.result.total[v].number.toFixed(1) }}</span>
              </el-tooltip>
              <span v-else>已分配：{{ scope.row.result.total[v].number.toFixed(1) }}</span>
            </div>
          </template>
      </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>
<script>
import { getHeaderName } from '@/app.config'
import http from '@/views/sys/axios'
import { mapState, mapMutations } from 'vuex'
import projectForm from './components/form.vue';
import shareDialog from './components/shareDialog.vue'
import checkManPower from './components/checkManPower.vue'
import { param } from '../../utils';

export default {
  components: {
    projectform: projectForm,
    ShareDialog: shareDialog,
    CheckManPowerDialog:checkManPower
  },
  data() {
    return {
      rowId:'',
      isshowHours:false,
      weekCol:[],
      gridData:[],
      projectList:[],
      isRescourceShow: 0,
      props: { multiple: true },
      projectListOptions:[],
      BACKEND_API: process.env.VUE_APP_SOURSE_MANAGE_HOST,
      dialogVisible: false,
      dialogEditVisible: false,
      shareVisible: false,
      checkManPowerVisible:false,
      tableData: [],
      tableTotal: 15,
      itemFormData:{},
      calculated:{},
      childData: [],
      expands: [],
      week_col: [],
      params: {
        pageNo: 1,
        pageSize: 10,
        project_ids: []
      },
      loading: false,
      statusList: [],
      shareId: '',
      logo: require('../../assets/question.png'),
      showHours:false,
    }
  },
  created() {
    this.getPorjectListOptions()
    this.getStatus()
    this.getPorjectList()
  },
  mounted() {
    this.$nextTick(() => {})
  },
  watch:{
    projectListOptions(){
      ++this.isRescourceShow
    }
  },
  methods: {
    
    showManPower(){
      this.checkManPowerVisible = true
    },
    week2date(val) {
      let arr = val.split("-")
      let year = arr[0]
      let week = arr[1]

      let betDay = new Date(year+1+'-01-01 00:00:00').getTime() - new Date(year+'-01-01 00:00:00').getTime()
      let newD1 = new Date(year,0,1)
      let newD2 = new Date(year,11,31)
      
      let dayMS=24*60*60*1000
      let firstDay=firstDay=(7-newD1.getDay())*dayMS
      let weekMS=0
      if(newD1.getDay() < 4) {
         weekMS=(week-2)*7*dayMS
      } else {
        weekMS=(week-1)*7*dayMS
      }
      let result=newD1.getTime()+firstDay+weekMS+5*dayMS
      newD1.setTime(result)
      return val + '周\n(' + newD1.getFullYear() + "/" + (newD1.getMonth()+1) + "/" +newD1.getDate() + ')'
    },
    addClass({row,column,rowIndex,columnIndex}){
      if(column.type == 'cell') {
        if(row.result.need[column.property].number != 0) { 
          if(row.result.need[column.property].number == row.result.total[column.property].number){
            return 'cell-green';
          }
          if(row.result.need[column.property].number > row.result.total[column.property].number){
              return 'cell-yellow';
          }
          if(row.result.need[column.property].number < row.result.total[column.property].number){
              return 'cell-red';
          }
        } else {
          if(row.result.total[column.property].number > 0){
            return 'cell-red';
          } else {
            return 'cell-grey';
          }
          
        }
        
      } else {
        return ''
      }
    },
    changeFilter(value) {
      this.params.pageNo = 1
      this.getPorjectList()
      
    },
    searchPro(e){
      this.projectList = [] // 清空参数
      e.map((v,i) => {
        this.projectList.push(v[1])
      })
      this.params.project_ids = this.projectList
      this.params.pageNo = 1
      this.getPorjectList()
    },
    getPorjectListOptions(){
      this.$axios({
        url: this.BACKEND_API + '/api/v1/project/tree_list',
        method: "get",
        headers: getHeaderName(),
      }).then(res => {
        this.projectListOptions = res.data.data
      })
    },
    getStatus() {
      this.$axios({
        url: this.BACKEND_API + '/api/v1/project/status',
        method: "get",
        headers: getHeaderName(),
      }).then(res => {
        this.statusList = res.data.data
      })
    },
    getPorjectList() {
      this.loading = true
      let params = Object.assign({},this.params) 
      for(let key in params){
        if(params[key] === '') {
          delete params[key]
        }
      }
      this.$axios({
        url: this.BACKEND_API + '/api/v1/car_project',
        method: "post",
        headers: getHeaderName(),
        data: params,
        traditional: true
      }).then(res => {
        res.data.data.data.map(item => {
          item.childData = []
        })
        this.tableData = res.data.data.data
        this.tableTotal = res.data.data.totalCount
        this.loading = false
      })
    },
    checkProject(row){
      this.rowId = row.id
      this.showHours = true
      this.isshowHours = true
      this.$axios({
            url: `${this.BACKEND_API}/api/v1/project/${row.id}/assign`,
            method: "get",
            headers: getHeaderName()
      }).then(res => {
        if(res.data.code===200){
          this.gridData = res.data.data
          let week = {}
          let listArr = []
          this.weekCol=[]
          if(res.data.data.length>0){
            week = res.data.data[0].result.need
            for(let key in week){
              listArr.push({
                key:key,
              })
            }
            this.compFnWeek(listArr)
            listArr.map(item => {
              this.weekCol.push(item.key)
            })
            this.weekCol=Array.from(new Set(this.weekCol))
          }
          let indexNa = ''
          indexNa = '#innerTable' 
          if(res.data.data[0] && res.data.data[0].index >= 0 && indexNa) {
            setTimeout(() => {
              $('#innerTable').find('.el-table__body-wrapper')[0].scrollLeft = parseInt(res.data.data[0].index) * 120
              this.isshowHours = false
            },500)
          }else{
            this.isshowHours = false
          }
          
        }
      })
    },
    //周排序
    compFnWeek(arr){
      arr.forEach(item=>{
        item.list=item.key.split('-')
        item.days=Number(item.list[0])*365+Number(item.list[1])*7
      })
      arr.sort((a,b)=>{
        return a.days -b.days
      })
    },
    getChildList(row, rowList) {
      if (rowList.length) { // 只展开一行//说明展开了
        this.expands = []
        let indexName = ''
        if (row) {
          this.expands.push(row.id)// 只展开当前行id
          this.$axios({
            url: `${this.BACKEND_API}/api/v1/project/${row.id}/assign`,
            method: "get",
            headers: getHeaderName()
          }).then(res => {
            this.tableData.forEach((temp, index) => {
              // 找到当前点击的行，把动态获取到的数据赋值进去
              if (temp.id === row.id) {
                this.tableData[index].childData = res.data.data
                indexName = '#innerTable' + row.id
              }
              if(res.data.data[0] && res.data.data[0].index >= 0 && indexName) {
                $(indexName).find('.el-table__body-wrapper')[0].scrollLeft = parseInt(res.data.data[0].index) * 120
              }
            });
          })
        }
      } else { // 说明收起了
        this.expands = []
      }
      
    },
    getFormDataByProjectNameEdit(project_name){
      this.$axios({
        url: this.BACKEND_API + '/api/v1/project/apply?project_name='+project_name,
        method: "get",
      }).then(res => {
        this.itemFormData = res.data.data.form
        this.calculated = res.data.data.calculated
      })
    },
    getFormDataByProjectNameDetails(project_name){
      this.$axios({
        url: this.BACKEND_API + '/api/v1/project/apply?project_name='+project_name,
        method: "get",
      }).then(res => {
        this.itemFormData = res.data.data.form
        this.calculated = res.data.data.calculated
        this.dialogVisible = true
      })
    },
    createProject(){
      this.$router.push({ name: 'resourceCreate', params: { id: '' } })
    },
    viewProject(id){
      this.$router.push({ name: 'resourceView', params: { id: id } })
    },
    editProject(row){
      let type = row.get_total_person_weeks == 0 ? true : false
      this.$router.push({ name: 'resourceAdd', params: { id: row.id, type:  type} })

    },
    delProject(id){
      this.$axios({
        url: this.BACKEND_API + '/api/v1/project/' + id,
        method: "delete",
        headers: getHeaderName(),
      }).then(res => {
        if(res.data.code == 200) {
          this.$message.success(res.data.message)
        } else {
          this.$message.error(res.data.message)
        }
          this.getPorjectList()
      })
    },
    editProjectOver(){
      this.dialogEditVisible = false
      this.getPorjectList()
    },
    tableCurrentChange(val) {
      this.params.pageNo = val
      this.getPorjectList()
    },
    tableSizeChange(val) {
      this.params.pageSize = val
      this.getPorjectList()
    },
    shareProject(id) {
      this.shareId = id
      this.shareVisible = true
      
    }
  }
}

</script>
<style lang="scss" scoped>
@import '../../assets/common/common.scss';

/deep/ .el-table th.gutter {
  display: table-cell !important;
}

/deep/ .el-dialog {
  min-height: 400px;
}

/deep/ .el-dialog__body {
  border-top: 1px solid #b2b2b2;
}

/deep/ .el-divider__text {
  color: #ffffff;
  font-size: 20px;
  font-weight: 600;
  background-color: #e6a23c;
  padding: 6px 16px;
}

/deep/ .el-divider--horizontal {
  margin: 40px 0;
  height: 2px;
}
/deep/ .el-table td.cell-grey { 
  background-color:#909399 !important;
  color: #fff;
}
/deep/ .el-table td.cell-red { 
  background-color:#ff4949 !important;
  color: #fff;
}
/deep/ .el-table td.cell-yellow { 
  background-color:#ffba00 !important;
  color: #fff;
}
/deep/ .el-table td.cell-green { 
  background-color:#13ce66 !important;
  color: #fff;
}
/deep/ .el-table .cell {
  white-space: pre-line;
}
.icon-item {
  float: right;
  margin-top: 15px;
  cursor: pointer;
}
.icon-item img {
  width: 30px;
  height: 30px;
}
.hover-div {
  cursor: pointer;
}
.borders{
  border-bottom: 1px solid #dfe6ec;
}

#wrapper {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;
}

.box {
  display: flex;

  div {
    margin: auto;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity .5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.toTop {
  position: fixed;
  bottom: 80px;
  right: 25px;
  z-index: 10;
}

.details {
  color: #1890ff;
  text-decoration: underline;
  cursor: pointer;
}

.choose {
  padding: 20px 0;

  .flex-box {
    display: flex;
    flex-wrap: nowrap;

    .flexEl {
      flex: 1;
      margin: auto;
    }

    .text-align {
      text-align: center;
    }

    .el {
      flex: 0 0 90%;
    }
  }

  .time {
    position: absolute;
    top: 20px;
    right: 41%;
    font-size: 14px;
    color: #606266;
  }

  .newReport {
    position: absolute;
    top: 20px;
    right: 20px;
  }
}

.border {
  box-sizing: content-box;
  height: 0;
  overflow: visible;
  margin-top: 1rem;
  margin-bottom: 1rem;
  border: 0;
  border-top: 1px solid rgba(0, 0, 0, .1);
}

.primary {
  color: #409EFF;
  font-size: 30px;
  margin-top: 20px;
  margin-bottom: 10px;
  font-weight: 400;
}

.bgColor {
  background: #fff;
}

.pad {
  padding: 0 20px;
  padding-top: 20px;
}

.marT {
  margin-top: 20px;
}

.btn-group {
  text-align: right;
}

.mar {
  margin: 0 20px;
  margin-top: 20px;
}

.table {
  padding-bottom: 10px;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

</style>
